package com.gmail.hh.flickrj.sample.android.fragments;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.LinearLayout;

import com.gmail.hh.flickrj.sample.android.R;
import com.gmail.hh.flickrj.sample.android.data.DataManagerFlickr;
import com.gmail.hh.flickrj.sample.android.data.PhotoData;
import com.gmail.hh.flickrj.sample.android.data.PhotolistData;
import com.gmail.hh.flickrj.sample.android.data.PhotolistData.IPhotolistZoomChanged;
import com.gmail.hh.flickrj.sample.android.images.LazyAdapterPhotolist;
import com.gmail.hh.flickrj.sample.android.interfaces.IDataReadyListener;
import com.gmail.hh.flickrj.sample.android.interfaces.IPhotoSelectedListener;


@SuppressLint("NewApi")
public class FragmentPhotogrid extends Fragment 
							implements 
							IPhotolistZoomChanged,
							IDataReadyListener {

	private static final Logger logger = LoggerFactory.getLogger(FragmentPhotogrid.class);
	
	public static final String TAG = "fragment_photogrid";
	
	private Activity mActivity;
	private Vibrator mVibrator;
	private PhotolistData mPhotolistData;
	private LazyAdapterPhotolist mAdapterGrid;
	private LinearLayout photogrid_container;
	private GridView gridPhoto;
	private float previousPhotoListZoomFactor;
	
	// each Activity which uses this Fragment must implement this interface
	private IPhotoSelectedListener mCallbackPhotoSelected;



	@Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
		mActivity = activity;
        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception
        try {
        	mCallbackPhotoSelected = (IPhotoSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement IPhotoSelectedListener");
        }
	}
	

	@Override
	public void onCreate(Bundle arg0) {

		super.onCreate(arg0);
		setRetainInstance(true);
	}
	

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup vg, Bundle data) {
		// Inflate the  layout file.
		View view = inflater.inflate(R.layout.fragment_photogrid, null);
		
		this.photogrid_container = (LinearLayout) view.findViewById(R.id.photogrid_container);
		this.gridPhoto = (GridView) view.findViewById(R.id.gridPhoto);

        mVibrator = (Vibrator)mActivity.getSystemService(Context.VIBRATOR_SERVICE);
		return view;
	}

	@Override
	public void onViewCreated(View arg0, Bundle arg1) {
		super.onViewCreated(arg0, arg1);  
		
		
	    // onTouch Listener to List-view-containter  
		// (attention return: 1xfalse, 1xtrue; otherwise no scroll or no zoom!)
		this.gridPhoto.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View arg0, MotionEvent event) {
				mPhotolistData.applyTouchEvent(FragmentPhotogrid.this, event, null);
				// action for changing size of imageView is handled by callback onZoomFactorChanged
				return false;  	// stop propagation true/false
			}
		});
		this.photogrid_container.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View arg0, MotionEvent event) {
				mPhotolistData.applyTouchEvent(FragmentPhotogrid.this, event, null);
				// action for changing size of imageView is handled by callback onZoomFactorChanged
				return true;  	// stop propagation true/false
			}
		});
		
		// Listener for selecting an item of gridview
		this.gridPhoto.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
	            mVibrator.cancel();
		        PhotoData photoData = mAdapterGrid.getItem(position);
				mCallbackPhotoSelected.onPhotoSelected( photoData, mPhotolistData, position, 0l);
			}
		});

	}
	
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        // reload actual Data from DataManager
		if ( !hidden ) {  
	//		logger.error("Photogrid - changed to not hidden");
			boolean forceRefresh = false;
			this.reloadData(forceRefresh);
	    }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    
    // refresh (call also be invoked by external classes)
    public void reloadData(boolean forceRefresh) {
    	if (forceRefresh)  {
    	    DataManagerFlickr.getInstance().loadPhotostreamUser(this);
    	    // test: vibrate-array in ms:   wait, on, off, on, off, on, off....
         //   mVibrator.vibrate( new long[]{ 500, 300, 600, 100, 2000 },0 );
        } else {
    	    onDataReady(true);
        }
    }
	
    
	
    
    // a new/actualized Data-Object is available by DataManager
	@Override
	public void onDataReady(boolean success) {
		if (success)  {
			PhotolistData photolistData_old = mPhotolistData;
			mPhotolistData = DataManagerFlickr.getInstance().getPhotolistDataUser();
			// replace only when new versionCounter
			if (mPhotolistData!=null && ( !mPhotolistData.isEqualVersionCounter(photolistData_old) 
					|| mPhotolistData.getPhotolistZoomFactor()!=previousPhotoListZoomFactor ) ) {
				// set Adapter for GridView
				this.createNewAdapter();  
			}
	    }
		
	}
	
	// set Adapter for GridView
	// after zooming the size of the actually viewable images of the list is not changed when no new adapter is created
	public void createNewAdapter() {	
		mAdapterGrid = new LazyAdapterPhotolist(getActivity(), mPhotolistData );
		mAdapterGrid.setLayoutResource(LazyAdapterPhotolist.LAYOUT_RESOURCE_GRID);

		gridPhoto.setAdapter(mAdapterGrid);
		
		// width available after rendering, but here we need it already before rendering
		int thumbsizeWidthDip = 76;  //dft 
		String thumbsizeWidthString = getResources().getString(R.string.photogrid_thumbsize_width);
		if (thumbsizeWidthString!=null && thumbsizeWidthString.indexOf("dip")>0 ) {
			thumbsizeWidthString = thumbsizeWidthString.substring(0, thumbsizeWidthString.length()-3);
			try {
				thumbsizeWidthDip = Integer.valueOf(thumbsizeWidthString);
			} catch (NumberFormatException e) {
			}	
			   
		}	
		// get dip-value and convert to pixel
		float thumbsizeWidthPx = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 
				thumbsizeWidthDip, getResources().getDisplayMetrics() );

		gridPhoto.setColumnWidth( (int) (thumbsizeWidthPx * mPhotolistData.getPhotolistZoomFactor()) );
		previousPhotoListZoomFactor = mPhotolistData.getPhotolistZoomFactor();   // save last zoomFactor
	}
	
	@Override
	public void onZoomFactorChangedAfterMoved(float zoomFactor) {
		this.createNewAdapter();  // rebuild 
	}
	@Override
	public void onZoomFactorChangedAfterFinished(float zoomFactor) {
		this.createNewAdapter();  // rebuild 
	}



	





	
	

}
